<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人力资源汇总管理</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 1800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }
        
        .header p {
            margin: 0;
            opacity: 0.9;
            font-size: 16px;
        }
        
        .control-panel {
            background-color: white;
            padding: 25px;
            border-bottom: 1px solid #e9ecef;
            border-left: 4px solid #67c23a;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .control-panel h2 {
            color: #2c3e50;
            margin: 0 0 15px 0;
            font-size: 20px;
            font-weight: 500;
        }
        
        .table-section {
            padding: 25px;
        }
        
        .table-section h2 {
            color: #2c3e50;
            margin: 0 0 20px 0;
            font-size: 20px;
            font-weight: 500;
        }
        
        .editable-table {
            border: 1px solid #ebeef5;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .editable-table .el-table__header-wrapper {
            background-color: #f5f7fa;
        }
        
        .editable-table .el-table__body-wrapper {
            background-color: white;
        }
        
        .editable-cell {
            padding: 4px;
            border: none;
            background: transparent;
            width: 100%;
            text-align: center;
            font-size: 14px;
        }
        
        .editable-table .el-table__body td {
            padding: 4px 0;
        }
        
        .editable-table .el-table__header th {
            padding: 8px 0;
        }
        
        .editable-cell:focus {
            outline: 2px solid #409eff;
            background-color: #f0f9ff;
        }
        
        .action-buttons {
            margin-top: 20px;
            text-align: center;
        }
        
        .action-buttons .el-button {
            margin: 0 10px;
        }
        
        .summary-stats {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            flex: 1;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-card h3 {
            margin: 0 0 10px 0;
            font-size: 16px;
            opacity: 0.9;
        }
        
        .stat-card .number {
            font-size: 24px;
            font-weight: bold;
        }
        
        .division-header {
            background-color: #e6f7ff !important;
            font-weight: 600;
            color: #1890ff;
        }
        
        .bu-header {
            background-color: #f6ffed !important;
            font-weight: 500;
            color: #52c41a;
        }
        
        .function-header {
            background-color: #fff7e6 !important;
            font-weight: 500;
            color: #fa8c16;
        }
        
        .month-header {
            background-color: #f0f9ff !important;
            font-weight: 500;
            color: #409eff;
            text-align: center;
        }
        
        .user-header {
            background-color: #f8f9fa !important;
            font-weight: 500;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="container">
            <!-- 顶部标题 -->
            <div class="header">
                <h1>人力资源汇总管理</h1>
                <p>Human Resource Summary Management</p>
            </div>
            
            <!-- 控制面板 -->
            <div class="control-panel">
                <h2>🎛️ 数据汇总控制台</h2>
                
                <!-- 汇总统计 -->
                <div class="summary-stats">
                    <div class="stat-card">
                        <h3>总用户数</h3>
                        <div class="number">{{ totalUsersCount }}</div>
                    </div>
                    <div class="stat-card">
                        <h3>已填写用户</h3>
                        <div class="number">{{ filledUsersCount }}</div>
                    </div>
                    <div class="stat-card">
                        <h3>总数据量</h3>
                        <div class="number">{{ totalDataCount }}</div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <el-button type="primary" @click="saveAllData">💾 保存所有数据</el-button>
                    <el-button type="success" @click="exportAllData">📊 导出所有数据</el-button>
                    <el-button type="warning" @click="clearAllData">🔄 清空所有数据</el-button>
                    <el-button type="info" @click="refreshData">📂 刷新数据</el-button>
                </div>
            </div>
            
            <!-- 表格区域 -->
            <div class="table-section" v-if="flatTableData.length > 0">
                <h2>📊 人力资源需求汇总表</h2>
                
                <div class="editable-table">
                    <el-table :data="flatTableData" border style="width: 100%">
                        <el-table-column prop="division" label="Division" min-width="120" align="center">
                            <template slot-scope="scope">
                                <span class="division-header">{{ scope.row.division }}</span>
                            </template>
                        </el-table-column>
                        
                        <el-table-column prop="bu" label="BU" min-width="100" align="center">
                            <template slot-scope="scope">
                                <span class="bu-header">{{ scope.row.bu }}</span>
                            </template>
                        </el-table-column>
                        
                        <el-table-column prop="function" label="Function" min-width="120" align="center">
                            <template slot-scope="scope">
                                <span class="function-header">{{ scope.row.function }}</span>
                            </template>
                        </el-table-column>
                        
                        <el-table-column prop="category" label="Category" min-width="150" align="center">
                            <template slot-scope="scope">
                                {{ scope.row.category }}
                            </template>
                        </el-table-column>
                        
                        <el-table-column v-for="month in months" :key="month" :label="month" min-width="80" align="center">
                            <template slot-scope="scope">
                                <input 
                                    v-model="scope.row[month]" 
                                    type="number" 
                                    step="0.1" 
                                    min="0"
                                    class="editable-cell"
                                    @input="calculateTotals"
                                    @blur="validateInput(scope.row, month)"
                                >
                            </template>
                        </el-table-column>
                        

                    </el-table>
                </div>
            </div>
            
            <!-- 无数据提示 -->
            <div class="table-section" v-else>
                <el-empty description="暂无用户数据，请先在填报页面填写数据">
                    <el-button type="primary" @click="goToIndex">前往填报页面</el-button>
                </el-empty>
            </div>
        </div>
    </div>

    <!-- 引入Vue.js -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- 引入Element UI -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    months: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
                    flatTableData: [],
                    allUsersData: {}
                }
            },

            computed: {
                totalUsersCount() {
                    return Object.keys(this.allUsersData).length;
                },
                
                filledUsersCount() {
                    return Object.values(this.allUsersData).filter(userData => 
                        userData.tableData && userData.tableData.length > 0
                    ).length;
                },
                
                totalDataCount() {
                    return this.flatTableData.length;
                }
            },

            mounted() {
                this.loadAllUsersData();
                this.generateFlatTableData();
            },
            
            methods: {
                loadAllUsersData() {
                    // 从localStorage加载所有用户数据
                    const allData = localStorage.getItem('allUsersData');
                    if (allData) {
                        try {
                            this.allUsersData = JSON.parse(allData);
                        } catch (error) {
                            console.error('加载用户数据失败:', error);
                            this.allUsersData = {};
                        }
                    }
                    
                    // 如果没有汇总数据，尝试从单个用户数据加载
                    if (Object.keys(this.allUsersData).length === 0) {
                        this.loadFromIndividualData();
                    }
                },
                
                loadFromIndividualData() {
                    // 尝试从index页面的数据格式加载
                    const hrTableData = localStorage.getItem('hrTableData');
                    if (hrTableData) {
                        try {
                            const data = JSON.parse(hrTableData);
                            const userId = 'default_user';
                            this.allUsersData[userId] = {
                                userId: userId,
                                userName: '默认用户',
                                lastUpdate: data.timestamp || new Date().toISOString(),
                                tableData: data.tableData || []
                            };
                        } catch (error) {
                            console.error('加载单个用户数据失败:', error);
                        }
                    }
                },
                
                generateFlatTableData() {
                    this.flatTableData = [];
                    
                    Object.values(this.allUsersData).forEach(userData => {
                        if (userData.tableData && userData.tableData.length > 0) {
                            userData.tableData.forEach(row => {
                                // 只处理数据行，跳过分类标题行和总计行
                                if (!row.isCategory && !row.isTotal) {
                                    const flatRow = {
                                        division: this.getDivisionFromBU(row.bu),
                                        bu: this.getBUName(row.bu),
                                        function: row.function,
                                        category: row.category,
                                        userName: userData.userName,
                                        submitTime: userData.lastUpdate
                                    };
                                    
                                    // 添加月份数据
                                    this.months.forEach(month => {
                                        flatRow[month] = row[month] || 0;
                                    });
                                    
                                    this.flatTableData.push(flatRow);
                                }
                            });
                        }
                    });
                },
                
                getBUName(bu) {
                    // 如果bu是对象，返回name字段；如果是字符串，直接返回
                    if (typeof bu === 'object' && bu !== null) {
                        return bu.name || bu.id || '未知BU';
                    }
                    return bu || '未知BU';
                },
                
                getDivisionFromBU(bu) {
                    // 如果bu是对象，从division字段获取；否则使用默认逻辑
                    if (typeof bu === 'object' && bu !== null && bu.division) {
                        return bu.division.name || bu.division.id || '未知Division';
                    }
                    
                    // 根据BU确定Division，这里可以根据实际需求调整
                    if (bu === 'BU1') {
                        return 'Division1';
                    } else if (bu === 'BU2') {
                        return 'Division2';
                    } else {
                        return 'Division1'; // 默认值
                    }
                },
                
                saveAllData() {
                    // 将修改后的数据保存回allUsersData
                    const userDataMap = {};
                    
                    // 按用户分组数据
                    const userGroups = {};
                    this.flatTableData.forEach(row => {
                        if (!userGroups[row.userName]) {
                            userGroups[row.userName] = [];
                        }
                        userGroups[row.userName].push(row);
                    });
                    
                    // 转换为原始格式并保存
                    Object.keys(userGroups).forEach(userName => {
                        const userData = Object.values(this.allUsersData).find(u => u.userName === userName);
                        if (userData) {
                            const convertedData = this.convertFlatToOriginal(userGroups[userName]);
                            userDataMap[userData.userId] = {
                                userId: userData.userId,
                                userName: userName,
                                lastUpdate: new Date().toISOString(),
                                tableData: convertedData
                            };
                        }
                    });
                    
                    this.allUsersData = userDataMap;
                    localStorage.setItem('allUsersData', JSON.stringify(this.allUsersData));
                    this.$message.success('所有数据已保存');
                },
                
                convertFlatToOriginal(flatRows) {
                    const originalData = [];
                    const categories = ['维修', '质量', '生产'];
                    const bus = ['BU1', 'BU1', 'BU2'];
                    
                    categories.forEach((category, index) => {
                        // 添加分类标题行
                        originalData.push({
                            bu: bus[index],
                            category: category,
                            isCategory: true,
                            subcategory: 'Total'
                        });
                        
                        // 添加子分类行
                        const subcategories = ['Permanent', 'Overtime/FTE', 'Temporary'];
                        subcategories.forEach(subcategory => {
                            const matchingRow = flatRows.find(row => 
                                row.function === category && row.category === subcategory
                            );
                            
                            const row = {
                                bu: bus[index],
                                category: category,
                                subcategory: subcategory,
                                isCategory: false,
                                isTotal: true
                            };
                            
                            // 添加月份数据
                            this.months.forEach(month => {
                                row[month] = matchingRow ? (matchingRow[month] || 0) : 0;
                            });
                            
                            originalData.push(row);
                        });
                    });
                    
                    return originalData;
                },
                
                refreshData() {
                    this.loadAllUsersData();
                    this.generateFlatTableData();
                    this.$message.success('数据已刷新');
                },
                
                clearAllData() {
                    this.$confirm('确定要清空所有用户的数据吗？此操作不可恢复！', '清空确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.allUsersData = {};
                        this.flatTableData = [];
                        localStorage.removeItem('allUsersData');
                        localStorage.removeItem('hrTableData');
                        this.$message.success('所有数据已清空');
                    }).catch(() => {
                        this.$message.info('已取消清空');
                    });
                },
                
                exportAllData() {
                    if (this.flatTableData.length === 0) {
                        this.$message.warning('没有可导出的数据');
                        return;
                    }
                    
                    // 创建CSV格式的数据
                    let csvContent = "Division,BU,Function,Category," + this.months.join(',') + ",填报人,填报时间\n";
                    
                    this.flatTableData.forEach(row => {
                        const rowData = [
                            row.division,
                            row.bu,
                            row.function,
                            row.category,
                            ...this.months.map(month => row[month] || 0),
                            row.userName,
                            this.formatDate(row.submitTime)
                        ];
                        csvContent += rowData.join(',') + '\n';
                    });
                    
                    // 创建下载链接
                    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                    const link = document.createElement('a');
                    const url = URL.createObjectURL(blob);
                    link.setAttribute('href', url);
                    link.setAttribute('download', `人力资源需求汇总表_${new Date().toISOString().split('T')[0]}.csv`);
                    link.style.visibility = 'hidden';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    
                    this.$message.success('所有数据已导出为CSV文件');
                },
                
                calculateTotals() {
                    // 触发计算属性更新
                    this.$forceUpdate();
                },
                
                validateInput(row, month) {
                    const value = parseFloat(row[month]);
                    if (isNaN(value) || value < 0) {
                        row[month] = 0;
                        this.$message.warning('请输入有效的非负数');
                    } else {
                        row[month] = value;
                    }
                },
                
                formatDate(dateString) {
                    if (!dateString) return '未知';
                    const date = new Date(dateString);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}`;
                },
                
                goToIndex() {
                    window.open('index.html', '_blank');
                }
            }
        });
    </script>
</body>
</html> 